package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<CourseCategoryTreeDto> queryTreeNode(String id) {
        List<CourseCategoryTreeDto> categoryTreeDtos=courseCategoryMapper.selectTreeNode(id);
        List<CourseCategoryTreeDto> listResult=new ArrayList<>();
        Map<String, CourseCategoryTreeDto> matTmp = categoryTreeDtos.stream()
                .filter(item -> !id.equals(item.getId()))
                .collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));

        categoryTreeDtos.stream()
                .filter(item->!id.equals(item.getId()))
                .forEach(item->{
                    if(item.getParentid().equals(id)){
                        listResult.add(item);
                    }

                    CourseCategoryTreeDto courseCategoryTreeDto = matTmp.get(item.getParentid());
                    if(courseCategoryTreeDto!=null){
                        if(courseCategoryTreeDto.getChildrenThreeNodes()==null) {
                            courseCategoryTreeDto.setChildrenThreeNodes(new ArrayList<CourseCategoryTreeDto>());
                        }
                        courseCategoryTreeDto.getChildrenThreeNodes().add(item);
                    }

                });

        return listResult;
    }
}
